#include <iostream>
#include <iomanip>
using namespace std;

const int MAX = 100;
const int FIELD_WIDTH = 5;

void printSpiralMatrix(int order)
{
	if (order < 0)
	{
		cout << "不存在" << order << "阶螺旋矩阵！" << endl;
		return;
	}

	//以一维数组代替二维数组进行动态声明
	int* a = new int[order * order];
	if (!a)
	{
		cout << "内存申请错误！" << endl;
		exit(1);
	}

	//矩阵螺旋方向枚举
	enum directions { up = -1, down = 1, left = -2, right = 2 };
	int direction = right;

	int rowIndex = (order - 1) / 2,
		colIndex = (order - 1) / 2,
		count = 1,
		i;

	*(a + rowIndex * order + colIndex) = count++;

	//核心算法：根据螺旋方向顺序，每两个方向有n次（n依次取1，2，3，...，order-1）相同方向延伸，但最后（n=order-1）有三个方向延伸
	for (i = 1; i < order; i++)
	{
		for (int j = 1; j <= 2; j++)
		{
			for (int k = 1; k <= i; k++)
			{
				if (direction == up)
				{
					rowIndex--;
				}
				else if (direction == down)
				{
					rowIndex++;
				}
				else if (direction == left)
				{
					colIndex--;
				}
				else if (direction == right)
				{
					colIndex++;
				}
				*(a + rowIndex * order + colIndex) = count++;
			}

			if (direction == up)
			{
				direction = right;
			}
			else if (direction == down)
			{
				direction = left;
			}
			else if (direction == left)
			{
				direction = up;
			}
			else if (direction == right)
			{
				direction = down;
			}
		}
	}
	//奇偶矩阵最后一次的最后一个方向的填充方式不同
	if (order % 2)
	{
		count = *a;
		for (i = 1; i < order; i++)
		{
			*(a + i) = ++count;
		}
	}
	else
	{
		count = *(a + order * order - 1);
		for (i = order - 2; i > -1; i--)
		{
			*(a + order * (order - 1) + i) = ++count;
		}
	}

	//格式打印
	for (i = 0; i < order; i++)
	{
		for (int j = 0; j < order; j++)
		{
			cout << setw(FIELD_WIDTH) << setiosflags(ios::left) << *(a + i * order + j);
		}
		cout << endl;
	}

	delete[] a;
}

int main()
{
	int i,
		a[MAX];

	cout << "请输入螺旋矩阵的阶数（0作结束标志）：";
	i = -1;
	do
	{
		i++;
		cin >> a[i];
	} while (a[i]);

	i = 0;
	while (a[i])
	{
		cout << "第" << i + 1 << "组螺旋矩阵（" << a[i] << "阶）：" << endl;
		printSpiralMatrix(a[i]);
		cout << endl;
		i++;
	}

	system("pause");
	return 0;
}